﻿using System.Collections.Generic;
using System.Windows;

namespace ibba.src.noriskbo
{
    public static class AsyncSingletonVeiculoLegal
    {
        public delegate void EndAsyncResult(List<ServiceCorporativo.Empresa> pEndAsyncResult);
        private static event EndAsyncResult OnEndAsyncResult;

        private static readonly object syncLock = new object();

        private static List<ServiceCorporativo.Empresa> _instance;
        private static bool _inProgress = false;

        public static void ObterLista(EndAsyncResult pEndAsyncResult)
        {
            lock (syncLock)
            {
                if (_instance == null)
                {
                    OnEndAsyncResult += pEndAsyncResult;

                    if (_inProgress == false)
                    {
                        _inProgress = true;

                        ServiceFactory.Instance.ServiceCorporativo.BeginObterEmpresas((pAsyncResult) =>
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(delegate()
                            {
                                var retorno = ((ServiceCorporativo.ICorporativo)pAsyncResult.AsyncState).EndObterEmpresas(pAsyncResult);

                                _instance = retorno;

                                lock (syncLock)
                                {
                                    _inProgress = false;
                                }

                                OnEndAsyncResult(_instance);
                                OnEndAsyncResult = null;
                            });

                        }, ServiceFactory.Instance.ServiceCorporativo);
                    }
                }
                else
                {
                    pEndAsyncResult(_instance);
                }

            }
        }

        public static void Release()
        {
            _instance = null;
        }
    }
}
